package com.jt.demo2.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import java.lang.annotation.Target;
import java.util.Arrays;

//Aop 面向切面编程
@Component
@Aspect //标识当前类是一个切面
@EnableAspectJAutoProxy //让AOP有效
public class TxAspect {
//    @Pointcut("within(com.jt.demo2.service.*)")
//    @Pointcut("execution(void com.jt.demo2.service.UserServiceImpl.addUser())")
//    @Pointcut("execution(* com.jt.demo2.service..*.*(..))")
@Pointcut("@annotation(com.jt.demo2.anno.TX)")
    public void pointCut(){
    }
    //通知方法，对原有的方法进行扩展
    @Before(value = "pointCut()")
    public void before(JoinPoint joinPoint){
//        //获取目标对象类型
//        Class targetClass = joinPoint.getTarget().getClass();
//        //获取目标对象名称
//        String targetName = joinPoint.getSignature().getDeclaringTypeName();
//        //获取目标方法名称
//        String methodName = joinPoint.getSignature().getName();
//        //获取参数数据
//        Object[] args = joinPoint.getArgs();
//        System.out.println("获取目标对象类型"+targetClass);
//        System.out.println("获取目标对象名称"+targetName);
//        System.out.println("获取目标方法名称"+methodName);
//        System.out.println("参数名称"+ Arrays.toString(args));

    }
    @AfterReturning(value = "pointCut()",returning = "result")
    public void AfterReturning(Object result){
        System.out.println("后置"+result);
    }
    @AfterThrowing(value = "pointCut()",throwing = "exeception")
    public void after(Exception exeception){
    exeception.printStackTrace();
        System.out.println("抛出异常"+exeception.getMessage());
    }
    @After("pointCut()")
    public void After(){
        System.out.println("最终通知");
    }
    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("环绕开始");
        //调用目标方法
        Object result = joinPoint.proceed();
        System.out.println("环绕结束");
        return result;
    }
}
